import {Player} from "./base/Player";
import {HeroData} from "../data/HeroData";

export class PlayerData{
    static MAX_PLAYER;
    static HERO_LOCAL_SEAT = 0;
    private static players:Array<Player>;
    static init(maxPlayer:number,heroLocalSeat?:number){
        PlayerData.MAX_PLAYER = maxPlayer;
        if(heroLocalSeat) PlayerData.HERO_LOCAL_SEAT = heroLocalSeat;
        PlayerData.players = new Array();
    }

    static exit(){
        PlayerData.players = new Array();
    }

    static addPlayer(player:Player):Player{
        PlayerData.delPlayerByUserID(player.uid);
        PlayerData.players.push(player);
        return player;
    }

    static delPlayerByUserID(uid){
        for(let i=0;i<PlayerData.players.length;i++){
            if(PlayerData.players[i].uid == uid){
                PlayerData.players.splice(i,1);
            }
        }
    }

    static getPlayerByServerSeat(serverSeat:number):Player|null{
        for(let i=0;i<PlayerData.players.length;i++){
            if(PlayerData.players[i].seat == serverSeat){
                return PlayerData.players[i];
            }
        }
        return null;
    }

    static getPlayerByLocalSeat(localSeat:number):Player|null{
        let serverSeat = PlayerData.localSeatToSeverSeat(localSeat);
        return PlayerData.getPlayerByServerSeat(serverSeat);
    }

    static getPlayerByUserID(uid:number){
        for(let i=0;i<PlayerData.players.length;i++){
            if(uid == PlayerData.players[i].uid){
                return PlayerData.players[i];
            }
        }
        return null;
    }

    static isHero(uid){
        return HeroData.uid == uid;
    }

    static getHero(){
        for(let i=0;i<PlayerData.players.length;i++){
            if(PlayerData.isHero(PlayerData.players[i].uid)){
                return PlayerData.players[i];
            }
        }
        return null;
    }

    static localSeatToSeverSeat(localSeat){
        if (localSeat < 0 || localSeat > PlayerData.MAX_PLAYER){
            return PlayerData.MAX_PLAYER;
        }
        let hero = PlayerData.getHero();
        if(hero == null) return PlayerData.MAX_PLAYER;
        let seat = (localSeat - PlayerData.HERO_LOCAL_SEAT + PlayerData.MAX_PLAYER) % PlayerData.MAX_PLAYER;
        return (seat + hero.seat) % PlayerData.MAX_PLAYER;
    }

    static serverSeatToLocalSeat(serverSeat){
        if (serverSeat < 0 || serverSeat > PlayerData.MAX_PLAYER){
            return PlayerData.MAX_PLAYER;
        }
        let hero = PlayerData.getHero();
        if(hero == null) return PlayerData.MAX_PLAYER;
        let local = (serverSeat - hero.seat + PlayerData.MAX_PLAYER) % PlayerData.MAX_PLAYER
        return (local + PlayerData.HERO_LOCAL_SEAT) % PlayerData.MAX_PLAYER
    }
}